<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>win12扫雷</title>
    <style>
        body {
            font-family: sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
        }

        .container {
            background-color: #c0c0c0;
            border: 2px solid #808080;
            padding: 10px;
            box-shadow: 3px 3px 5px rgba(0, 0, 0, 0.3);
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
        }

        .game-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            padding: 5px;
            background-color: #c0c0c0;
            border: 1px solid #808080;
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
        }

        #timer, #mines-left {
            font-size: 1.2em;
            padding: 5px;
            background-color: black;
            color: red;
            width: 50px;
            text-align: center;
            border: 2px inset #808080;
        }

        .face-button {
            font-size: 1.5em;
            background-color: #c0c0c0;
            border: 2px solid #808080;
            cursor: pointer;
            padding: 5px 10px;
            border-style: outset;
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
        }

        .face-button:active {
            border-style: inset;
        }

        .grid {
            display: grid;
            border: 2px solid #808080;
            background-color: #c0c0c0;
            border-style: inset;
        }

        .cell {
            width: 25px;
            height: 25px;
            border: 2px solid #808080;
            box-sizing: border-box;
            text-align: center;
            font-size: 1.1em;
            cursor: pointer;
            border-style: outset;
            user-select: none;
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
            position: relative;
        }

        .cell:active {
            border-style: inset;
        }

        .cell.revealed {
            border-style: none;
            background-color: #d0d0d0;
            background: linear-gradient(to bottom, #d0d0d0, #e0e0e0);
        }

        .cell.mine {
            background-color: red;
            color: white;
        }

        .cell.flagged::before { /* 这里写完才知道忘加了 */
            content: "🚩";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 1.2em;
        }


        .win12-button {
            background-color: #c0c0c0;
            border: 2px solid #808080;
            border-style: outset;
            padding: 5px 10px;
            cursor: pointer;
            background: linear-gradient(to bottom, #c0c0c0, #d0d0d0);
        }

        .win12-button:active {
            border-style: inset;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: #fefefe;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            background: linear-gradient(to bottom, #f0f0f0, #f8f8f8);
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        .difficulty-selector {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }

        .custom-difficulty {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .custom-difficulty label {
            font-size: 14px;
        }

        .custom-difficulty input {
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="game-info">
        <div id="mines-left">0</div>
        <button class="face-button" id="reset-button">🙂</button>
        <div id="timer">0</div>
    </div>
    <div class="grid" id="grid"></div>

    <!-- Modal -->
    <div id="modal" class="modal">
        <div class="modal-content">
            <span class="close" id="close-modal">&times;</span>
            <h2>游戏结束！</h2>
            <p id="modal-message"></p>
            <button class="win12-button" id="restart-button">重新开始</button>
        </div>
    </div>

    <!-- 模式-->
    <div class="difficulty-selector">
        <button class="win12-button" data-difficulty="easy">简单 (9x9, 10雷)</button>
        <button class="win12-button" data-difficulty="medium">中等 (16x16, 40雷)</button>
        <button class="win12-button" data-difficulty="hard">困难 (16x30, 99雷)</button>
        <div class="custom-difficulty">
            <label for="custom-rows">行数:</label>
            <input type="number" id="custom-rows" value="16" min="5" max="30">
            <label for="custom-cols">列数:</label>
            <input type="number" id="custom-cols" value="16" min="5" max="30">
            <label for="custom-mines">雷数:</label>
            <input type="number" id="custom-mines" value="40" min="1" max="899">
            <button class="win12-button" id="custom-button">自定义</button>
        </div>
    </div>

</div>

<script>
    const gridElement = document.getElementById('grid');
    const minesLeftElement = document.getElementById('mines-left');
    const resetButton = document.getElementById('reset-button');
    const timerElement = document.getElementById('timer');
    const modal = document.getElementById('modal');
    const closeModalButton = document.getElementById('close-modal');
    const restartButton = document.getElementById('restart-button');
    const modalMessage = document.getElementById('modal-message');
    const difficultyButtons = document.querySelectorAll('.difficulty-selector button[data-difficulty]');
    const customButton = document.getElementById('custom-button');
    const customRowsInput = document.getElementById('custom-rows');
    const customColsInput = document.getElementById('custom-cols');
    const customMinesInput = document.getElementById('custom-mines');
    //好丑啊这里


    let grid = [];
    let rows = 9;
    let cols = 9;
    let mines = 10;
    let minesLeft = mines;
    let isGameOver = false;
    let timerInterval;
    let seconds = 0;
    let firstClick = true;


    function createGrid() {
        grid = [];
        for (let i = 0; i < rows; i++) {
            grid.push(Array(cols).fill(0));
        }
    }


    function placeMines(initialRow, initialCol) {
        let minesPlaced = 0;
        while (minesPlaced < mines) {
            const row = Math.floor(Math.random() * rows);
            const col = Math.floor(Math.random() * cols);

            if (grid[row][col] !== 'mine' && (row !== initialRow || col !== initialCol)) {
                grid[row][col] = 'mine';
                minesPlaced++;
            }
        }
    }



    function calculateNumbers() {
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                if (grid[i][j] !== 'mine') {
                    let count = 0;
                    for (let x = -1; x <= 1; x++) {
                        for (let y = -1; y <= 1; y++) {
                            if (i + x >= 0 && i + x < rows && j + y >= 0 && j + y < cols && grid[i + x][j + y] === 'mine') {
                                count++;
                            }
                        }
                    }
                    grid[i][j] = count;
                }
            }
        }
    }


    function renderGrid() {
        gridElement.innerHTML = '';
        gridElement.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;

        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                const cell = document.createElement('div');
                cell.classList.add('cell');
                cell.dataset.row = i;
                cell.dataset.col = j;

                cell.addEventListener('click', handleCellClick);
                cell.addEventListener('contextmenu', handleCellRightClick);

                gridElement.appendChild(cell);
            }
        }
    }


    function handleCellClick(event) {
        if (isGameOver) return;

        const cell = event.target;
        const row = parseInt(cell.dataset.row);
        const col = parseInt(cell.dataset.col);

        if(firstClick) {
            placeMines(row, col);
            calculateNumbers();
            firstClick = false;
            startTimer();
        }


        if (cell.classList.contains('flagged')) return; // Ignore clicks on flagged cells

        revealCell(row, col);
    }

    function handleCellRightClick(event) {
        event.preventDefault(); // Prevent default context menu
        if (isGameOver) return;

        const cell = event.target;
        const row = parseInt(cell.dataset.row);
        const col = parseInt(cell.dataset.col);

        toggleFlag(row, col, cell);
    }

    function toggleFlag(row, col, cell) {
        if (grid[row][col] === 'revealed') return;

        if (cell.classList.contains('flagged')) {
            cell.classList.remove('flagged');
            minesLeft++;
        } else {
            if(minesLeft > 0){
                cell.classList.add('flagged');
                minesLeft--;
            }

        }
        minesLeftElement.textContent = minesLeft;
    }


    function revealCell(row, col) {
        if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] === 'revealed') return;

        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        if (!cell || cell.classList.contains('flagged')) return;


        if (grid[row][col] === 'mine') {
            cell.classList.add('mine', 'revealed');
            gameOver(false);
            return;
        }

        const value = grid[row][col];
        grid[row][col] = 'revealed';
        cell.classList.add('revealed');
        cell.textContent = value === 0 ? '' : value;


        if (value === 0) {
            for (let x = -1; x <= 1; x++) {
                for (let y = -1; y <= 1; y++) {
                    revealCell(row + x, col + y);
                }
            }
        }

        checkWin();
    }

    function gameOver(win) {
        isGameOver = true;
        stopTimer();
        resetButton.textContent = win ? "😎" : "🤯";

        // Reveal all mines
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                const cell = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
                if (grid[i][j] === 'mine' && cell) {
                    cell.classList.add('mine', 'revealed');
                }
            }
        }

        modalMessage.textContent = win ? "恭喜，你赢了！" : "游戏结束，你输了！";
        modal.style.display = "flex";
    }


    function checkWin() {
        let revealedCount = 0;
        for (let i = 0; i < rows; i++) {
            for (let j = 0; j < cols; j++) {
                if (grid[i][j] === 'revealed') {
                    revealedCount++;
                }
            }
        }
        if (revealedCount === rows * cols - mines) {
            gameOver(true);
        }
    }


    function resetGame() {
        isGameOver = false;
        stopTimer();
        seconds = 0;
        firstClick = true;
        timerElement.textContent = '0';
        resetButton.textContent = '🙂';
        minesLeft = mines;
        minesLeftElement.textContent = minesLeft;
        createGrid();
        renderGrid();
    }

    function startTimer() {
        timerInterval = setInterval(() => {
            seconds++;
            timerElement.textContent = seconds;
        }, 1000);
    }

    function stopTimer() {
        clearInterval(timerInterval);
    }


    // Event listeners
    resetButton.addEventListener('click', resetGame);

    closeModalButton.addEventListener('click', () => {
        modal.style.display = "none";
    });

    restartButton.addEventListener('click', () => {
        modal.style.display = "none";
        resetGame();
    });

    difficultyButtons.forEach(button => {
        button.addEventListener('click', () => {
            const difficulty = button.dataset.difficulty;
            if (difficulty === 'easy') {
                rows = 9;
                cols = 9;
                mines = 10;
            } else if (difficulty === 'medium') {
                rows = 16;
                cols = 16;
                mines = 40;
            } else if (difficulty === 'hard') {
                rows = 16;
                cols = 30;
                mines = 99;
            }
            resetGame();
        });
    });

    customButton.addEventListener('click', () => {
        const customRows = parseInt(customRowsInput.value);
        const customCols = parseInt(customColsInput.value);
        const customMines = parseInt(customMinesInput.value);

        if (customRows >= 5 && customRows <= 30 && customCols >= 5 && customCols <= 30 && customMines >= 1 && customMines < customRows * customCols) {
            rows = customRows;
            cols = customCols;
            mines = customMines;
            resetGame();
        } else {
            alert("自定义参数不合法，请重新设置。");
        }
    });


    // Initialize game
    resetGame(); // Start with default settings
</script>

</body>
</html>